import os
import sys
import sqlite3
import django
from django.conf import settings

# 添加项目路径
sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')

# 临时配置SQLite数据库来读取数据
SQLITE_DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': '../backend/db.sqlite3',
    }
}

def sync_data():
    """同步SQLite数据到MySQL"""
    
    # 首先运行MySQL迁移
    print("1. 运行MySQL数据库迁移...")
    os.system("cd ../backend && python manage.py migrate")
    
    # 连接SQLite数据库读取数据
    sqlite_db_path = '../backend/db.sqlite3'
    if not os.path.exists(sqlite_db_path):
        print("SQLite数据库文件不存在")
        return
    
    conn = sqlite3.connect(sqlite_db_path)
    cursor = conn.cursor()
    
    # 设置Django环境
    django.setup()
    
    from apps.flowers.models import Flower, FlowerImage, FlowerCategory
    from apps.users.models import User, UserAddress
    from apps.orders.models import Order, OrderItem
    
    print("2. 开始同步数据...")
    
    # 同步花卉分类
    print("同步花卉分类...")
    cursor.execute("SELECT * FROM flowers_flowercategory")
    categories = cursor.fetchall()
    for cat in categories:
        FlowerCategory.objects.get_or_create(
            id=cat[0],
            defaults={
                'name': cat[1],
                'description': cat[2] if len(cat) > 2 else '',
                'created_at': cat[3] if len(cat) > 3 else None,
                'updated_at': cat[4] if len(cat) > 4 else None,
            }
        )
    
    # 同步花卉
    print("同步花卉...")
    cursor.execute("SELECT * FROM flowers_flower")
    flowers = cursor.fetchall()
    for flower in flowers:
        Flower.objects.get_or_create(
            id=flower[0],
            defaults={
                'name': flower[1],
                'description': flower[2],
                'price': flower[3],
                'category_id': flower[4] if flower[4] else None,
                'stock': flower[5] if len(flower) > 5 else 100,
                'is_available': flower[6] if len(flower) > 6 else True,
                'created_at': flower[7] if len(flower) > 7 else None,
                'updated_at': flower[8] if len(flower) > 8 else None,
            }
        )
    
    # 同步花卉图片
    print("同步花卉图片...")
    cursor.execute("SELECT * FROM flowers_flowerimage")
    images = cursor.fetchall()
    for img in images:
        FlowerImage.objects.get_or_create(
            id=img[0],
            defaults={
                'flower_id': img[1],
                'image_url': img[2],
                'is_primary': img[3] if len(img) > 3 else False,
                'created_at': img[4] if len(img) > 4 else None,
            }
        )
    
    # 同步用户（如果存在）
    print("同步用户...")
    try:
        cursor.execute("SELECT * FROM users_user")
        users = cursor.fetchall()
        for user in users:
            User.objects.get_or_create(
                id=user[0],
                defaults={
                    'openid': user[1],
                    'nickname': user[2] if len(user) > 2 else '',
                    'avatar': user[3] if len(user) > 3 else '',
                    'phone': user[4] if len(user) > 4 else '',
                    'created_at': user[5] if len(user) > 5 else None,
                    'updated_at': user[6] if len(user) > 6 else None,
                }
            )
    except Exception as e:
        print(f"用户表同步失败: {e}")
    
    # 同步订单（如果存在）
    print("同步订单...")
    try:
        cursor.execute("SELECT * FROM orders_order")
        orders = cursor.fetchall()
        for order in orders:
            Order.objects.get_or_create(
                id=order[0],
                defaults={
                    'order_number': order[1],
                    'user_id': order[2] if order[2] else None,
                    'total_amount': order[3],
                    'status': order[4] if len(order) > 4 else 'pending',
                    'created_at': order[5] if len(order) > 5 else None,
                    'updated_at': order[6] if len(order) > 6 else None,
                }
            )
    except Exception as e:
        print(f"订单表同步失败: {e}")
    
    conn.close()
    print("3. 数据同步完成！")

if __name__ == "__main__":
    sync_data()